package com.fnfn.sdk.api.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.fnfn.sdk.api.common.DateUtil;
import com.fnfn.sdk.api.common.MySqlDBUtil;
import com.fnfn.sdk.api.dao.SysBackupMapper;
import com.fnfn.sdk.api.entity.SysBackup;
import com.fnfn.sdk.api.service.ISystemService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fnfn.sdk.api.LocalConfig;

@Service("iSystemService")
public class SystemServiceImpl implements ISystemService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SystemServiceImpl.class);

    private final LocalConfig localConfig;

    private final SysBackupMapper sysBackupMapper;

    @Autowired
    public SystemServiceImpl(LocalConfig localConfig, SysBackupMapper sysBackupMapper) {
        this.localConfig = localConfig;
        this.sysBackupMapper = sysBackupMapper;
    }

    @Override
    public void backup(String userId, String remark) throws Exception {
        String id = UUID.randomUUID().toString();
        String fileName = "backup_" + id + ".sql";
        String filePath = localConfig.getSystem_backup() + fileName;

        LOGGER.info("----------------filepath:{}", filePath);

        String username = localConfig.getUsernames();
        String password = localConfig.getPassword();
        String database = localConfig.getDatabase();

        MySqlDBUtil.backupDB(username, password, database, filePath);

        SysBackup sysBackup = new SysBackup();
        sysBackup.setId(id);
        sysBackup.setCreator(userId);
        sysBackup.setBackupFile(fileName);
        sysBackup.setStatus("1");
        sysBackup.setRemark(remark);
        sysBackup.setBackupTime(DateUtil.formatDate(new Date()));
        sysBackupMapper.insertSelective(sysBackup);
    }

    @Override
    public SysBackup selectByBackupTime(String date) throws Exception {
        return sysBackupMapper.selectByBackupDate(date);
    }

    @Override
    public SysBackup selectByPrimaryKey(String backupId) throws Exception {
        return sysBackupMapper.selectByPrimaryKey(backupId);
    }

    @Override
    public void removeById(String backupId) throws Exception {
        sysBackupMapper.removeById(backupId);
    }

    @Override
    public List<SysBackup> selectByCondition(SysBackup sysBackup) throws Exception {
        if (StringUtils.isNotEmpty(sysBackup.getEndDate())) {
            try {
                sysBackup.setEndDate(DateUtil.addDate(sysBackup.getEndDate(), 1));
            } catch (Exception e) {
            }
        }
        List<SysBackup> sysBackups = sysBackupMapper.selectByCondition(sysBackup);
        return sysBackups;
    }
}
